<?php
require_once("includes/header.php");


if(array_key_exists('action', $_GET)){
    if($_GET['action'] == 'delete'){
        
        $unlink_image = "SELECT [ID]
                        ,[Location_id]
                        ,[ImageURL]
                        ,[SR_id]
                    FROM [t_ServiceRequests_images]
                    where ID = '".$_POST['prji_id']."'";
       $unlink_result = $DBOBJ->select($unlink_image);
       
       
       $deleteSql = "DELETE FROM [t_ServiceRequests_images]
                    WHERE ID = '".$_POST['prji_id']."'";
       $DBOBJ->query($deleteSql);
        $path = $_SESSION['ROOT_PATH']."/upload/request/".$unlink_result[0]['ImageURL'];
       unlink($path);

       exit;
    }
}


$REQUESTED_DATA = $_POST;
$store_id = '';
$prob_desc = '';
$service_request_number = '';
$Location_id = '';
$req_status = '';
$errorMessage = Array();
$image_result = array();
//store query
$store_query = "SELECT [Store_ID],[Store_Name],[Store_Info]
                FROM [t_Stores]";
$store_result = $DBOBJ->select($store_query);

//location query
$location_query = "SELECT [ID],[Name]
                   FROM [location]";
$location_result = $DBOBJ->select($location_query);


if(array_key_exists('store_id', $_GET)){
    $store_id = $_GET['store_id'];
}

if(array_key_exists('id', $_GET)){
    $request_query = "SELECT  [SR_ID]
                        ,[Store_ID]
                        ,[Prob_Desc]
                        ,[Status]
                        ,[Submitted_On]
                        ,[Location_id]
                        ,[service_request_number]
                    FROM [t_ServiceRequests]
                    where [SR_ID] = '".$_GET['id']."'";
    $request_result = $DBOBJ->select($request_query);
    
    $store_id = $request_result[0]['Store_ID'];
    $prob_desc = $request_result[0]['Prob_Desc'];
    $service_request_number = $request_result[0]['service_request_number'];
    $Location_id = $request_result[0]['Location_id'];
    $req_status = $request_result[0]['Status'];
    
    
    $image_data = "SELECT [ID]
                    ,[Location_id]
                    ,[ImageURL]
                    ,[SR_id]
                FROM [t_ServiceRequests_images]
                where [SR_ID] = '".$_GET['id']."'";
    $image_result = $DBOBJ->select($image_data);
       
}



if($REQUESTED_DATA){
    $store_id = $REQUESTED_DATA['store_id'];
    $prob_desc = $REQUESTED_DATA['prob_desc'];
    $service_request_number = $REQUESTED_DATA['service_request_number'];
    $Location_id = $REQUESTED_DATA['Location_id'];
    $req_status = $REQUESTED_DATA['req_status'];
    


    
    
    if($store_id == ''){
        $errorMessage[] = 'Please select store';
    }if($service_request_number == ''){
        $errorMessage[] = 'Please select service number';
    }if($Location_id == ''){
        $errorMessage[] = 'Please select location';
    }if($req_status == ''){
        $errorMessage[] = 'Please select status';
    }
    if (count($errorMessage) <= 0) {
      if(array_key_exists('requestid', $REQUESTED_DATA)){
          $query_update ="UPDATE [t_ServiceRequests]
                            SET [Store_ID] = '".$store_id."'
                               ,[Prob_Desc] = '".$prob_desc."'
                               ,[Status] = '".$req_status."'
                               ,[Submitted_On] =  GETDATE()
                               ,[Location_id] = '".$Location_id."'
                               ,[service_request_number] =   '".$service_request_number."'
                          WHERE [SR_ID]  = '".$REQUESTED_DATA['requestid']."'";
         $update_result =   $DBOBJ->query($query_update);
         
         //image upload
         foreach ($_FILES["request_image"]["name"] as $key => $val){
             
             if($val != ''){
                $temp = explode(".", $val);
                $extension = end($temp);
                $fileName =  'request_'.rand()."_" . time() . '.' . $extension;

                if(move_uploaded_file($_FILES['request_image']["tmp_name"][$key], "upload/request/" . $fileName)) {

                                       $image_url = $_SESSION['IMAGE_URL'].$fileName;
                $request_image = "INSERT INTO [t_ServiceRequests_images]
                                   ([ID]
                                   ,[Location_id]
                                   ,[ImageURL]
                                   ,[SR_id])
                             VALUES
                                   ((SELECT CAST(NewID() AS UNIQUEIDENTIFIER))
                                   ,'".$Location_id."'
                                   ,'".$image_url."'
                                   ,'".$REQUESTED_DATA['requestid']."')";
                $request_imageresult =   $DBOBJ->insert($request_image);
                                   } else {
                                       
                                       $errorMessage[] = 'Error in uploading image';
                                   }
             }
         
         }
        
         
      }else{
       $insert_query = "INSERT INTO [t_ServiceRequests]
           ([Store_ID]
           ,[Prob_Desc]
           ,[Status]
           ,[Submitted_On]
           ,[Location_id]
           ,[service_request_number])
     VALUES
           ('".$store_id."','".$prob_desc."','".$req_status."',
            GETDATE(),   
            '".$Location_id."',
            '".$service_request_number."'
          )";
       
       $insert_result = $DBOBJ->insert($insert_query);
       
        
         foreach ($_FILES["request_image"]["name"] as $key => $val){
           // echo $val;
             if($val != ''){
                 
                $temp = explode(".", $val);
                $extension = end($temp);
                $fileName =  'request_'.rand()."_" . time() . '.' . $extension;
                
                if ( move_uploaded_file($_FILES['request_image']["tmp_name"][$key],"upload/request/" . $fileName) ) {
                    
                    $image_url = $_SESSION['IMAGE_URL'].$fileName;
                $request_image = "INSERT INTO [t_ServiceRequests_images]
                                   ([ID]
                                   ,[Location_id]
                                   ,[ImageURL]
                                   ,[SR_id])
                             VALUES
                                   ((SELECT CAST(NewID() AS UNIQUEIDENTIFIER))
                                   ,'".$Location_id."'
                                   ,'".$image_url."'
                                   ,'".$insert_result."')";
                $request_imageresult =   $DBOBJ->insert($request_image);    
                } else {
                    $errorMessage[] = 'Error in uploading image';
                }

                
                
             }
         
         }
        
      }
      if(array_key_exists('store_id', $_GET)){
        header("Location: location.php?store_id=".$store_id);  
      }else{
        header("Location: home.php");
      }
    }
    
}
?><script src="js/request.js"></script>

<div id="projectform"></div>
<div class="content">
    <div class="container-fluid">
        <div class="form-page" id="pad-wrapper">
            <div class="row-fluid form-wrapper">
                <div class="span column">
                    <h3>Add Request</h3>
                    <br>
                    <?php 
				if (count($errorMessage) > 0): ?>
				<div class="alert alert-error">
				<?php foreach ($errorMessage as $erroValue): ?>
				
					<div class="text-left">
					<i class="icon-remove-sign"></i>
					<?php echo $erroValue; ?>
					</div>
					
				<?php endforeach; ?>
				</div>
				<?php endif; ?>
                    
                    <form method="post" action="" enctype="multipart/form-data" name="request-form" id="request-form" role="form">
                        <div class="field-box">
                            <label>Store<span class="error-star">*</span>:</label>
                            <div class="ui-select">
                                <select id="store_id" name="store_id">
                                    <option value="">Select Store</option>
                                    <?php
                                    foreach ($store_result as $key => $value):
                                    
                                    if($value['Store_ID'] == $store_id){
                                        $checked = 'selected';
                                    }else{
                                        $checked = '';
                                    }
                                     ?>
                                    
                                     <option  <?php echo $checked;?> value="<?php echo $value['Store_ID']  ?>"><?php echo $value['Store_Name']  ?></option>
                                    <?php 
                                    endforeach;
                                    ?>
                                </select>    
                            </div>
                        </div>

                        <div class="field-box">
                            <label>Description:</label>
                            <textarea name="prob_desc" rows="5" cols="10" id="prob_desc"><?php echo $prob_desc;?></textarea>
                        </div>
                        
                         <div class="field-box">
                            <label>Request Number<span class="error-star">*</span>:</label>
                            <input type="text" id="service_request_number" name="service_request_number" value="<?php echo $service_request_number?>"> 
                        </div>
                        <div id="image_div" style="display: none">
                            <div class="field-box" id ="after_image" >
                                <label>Image:</label>
                                <input type="file" id="request_image" name="request_image[]">

                                <a href="#" class="add-cnt">
                                    <img width="28" height="28" src="img/plus.png" alt="Edit" title="Edit" />
                                </a>

                                 <a href="#" class="remove-cnt">
                                     <img width="28" height="28" src="img/minus.png" alt="Edit" title="Edit" />
                                 </a>
                            </div>
                        </div>
                        
                         <div class="field-box" id ="after_image" >
                                <label>Image:</label>
                                <input type="file" id="request_image" name="request_image[]">

                                <a href="#" class="add-cnt">
                                    <img width="28" height="28" src="img/plus.png" alt="Edit" title="Edit" />
                                </a>

                            </div>
                        <?php if (count($image_result) > 0): ?>
                <div class="pageoverflow">
                    <br>
                    <div class="pageinput">
                        <div class="table-overflow">
                        <div class="project-img">
                                    <?php foreach ($image_result as $_projectImages): ?>
                                        <?php
                                        $thumb_src_path = "upload/request/" . $_projectImages['ImageURL'];
                                        ?>
                                        <div style="float:left;">
                                                <img src="<?php echo $thumb_src_path; ?>" height="150" width="150"/>&nbsp;&nbsp;
                                        </div>
                                        <div style="float:left;">
                                            <a href="#" class="delete-image" imageid="<?php echo $_projectImages['ID']; ?>">
                                                <img width="28" height="28" src="img/false.gif" alt="Delete" title="Delete" />
                                            </a>
                                        </div>
                                        <div class='clear'></div>
                                        
                                        
                                    <?php endforeach; ?>
                            </ul>
                        </div>
                        </div>
                    </div>
                </div>
                        <div style="clear: both"></div>
                <?php endif; ?>
                
                        <div class="field-box">
                            <label>Location<span class="error-star">*</span>:</label>
                            <div class="ui-select">
                                <select id="Location_id" name="Location_id">
                                    <option value="">Select Location</option>
                                     <?php
                                    foreach ($location_result as $key => $value):
                                        if($value['ID'] == $Location_id){
                                            $checked = 'selected';
                                        }else{
                                            $checked = '';
                                        }
                                    ?>
                                     <option <?php echo $checked  ?> value="<?php echo $value['ID']  ?>"><?php echo $value['Name']  ?></option>
                                    <?php 
                                    endforeach;
                                    ?>
                                </select>    
                            </div>
                        </div>
                        
                        
                        <div class="field-box">
                            <label>Status<span class="error-star">*</span>:</label>
                            <div class="ui-select">
                                <select id="req_status" name="req_status">
                                    <option selected="selected" value="">-- Select Status --</option>
                                    <option value="Active" <?php if($req_status == 'Active' ): echo 'selected'; endif; ?>>Active</option>
                                    <option value="Inactive" <?php if($req_status == 'Inactive' ): echo 'selected'; endif; ?>>Inactive</option>
                                    <option value="Progress" <?php if($req_status == 'Progress' ): echo 'selected'; endif; ?>>Progress</option>
                                    <option value="Dispatched" <?php if($req_status == 'Dispatched' ): echo 'selected'; endif; ?>>Dispatched</option>
                                    <option value="Done" <?php if($req_status == 'Done' ): echo 'selected'; endif; ?>>Done</option>
                                    <option value="Waiting for Info" <?php if($req_status == 'Waiting for Info' ): echo 'selected'; endif; ?>>Waiting for Info</option>
                                    <option value="Hold" <?php if($req_status == 'Hold' ): echo 'selected'; endif; ?>>Hold</option>
                                </select>                       
                            </div> 
                        </div>

                        <br>
                        <div class="field-box">
                            <?php if(array_key_exists('id', $_GET)):?>
                            <input type="hidden" name="requestid" id="requestid" value="<?php echo $_GET['id']?>" />
                            <?php endif;?>
                            <input type="submit" class="btn-glow primary" title="Save changes" value="Save" id="Save" name="Save">
                            <input type="reset" class="btn-glow primary" title="Save changes and continue to edit" value="Reset" id="Reset" name="Reset"> 
                        </div>
                   </form>
                </div>
            </div>
        </div>
    </div>        </div>
<?php
require_once("includes/footer.php");
?>


